package com.authine.cloudpivot.ext.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import com.authine.cloudpivot.ext.mapper.*;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
// import org.springframework.jdbc.datasource.DataSourceTransactionManager;
// import org.springframework.transaction.TransactionDefinition;
// import org.springframework.transaction.TransactionStatus;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.util.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.xxpt.gateway.shared.api.request.OapiMoziEmployeeListEmployeePositionsByEmployeeCodeRequest;
import com.alibaba.xxpt.gateway.shared.api.request.OapiMoziEmployeeListEmployeesByCodesRequest;
import com.alibaba.xxpt.gateway.shared.api.request.OapiMoziOrganizationPageOrganizationEmployeeCodesRequest;
import com.alibaba.xxpt.gateway.shared.api.request.OapiOpenplatformMessageDeleteEventCallbackDefineRequest;
import com.alibaba.xxpt.gateway.shared.api.request.OapiOpenplatformMessageQueryCallbackDefineRequest;
import com.alibaba.xxpt.gateway.shared.api.request.OapiOpenplatformMessageQueryCallbackFailedRequest;
import com.alibaba.xxpt.gateway.shared.api.request.OapiOpenplatformMessageRegisterEventCallbackRequest;
import com.alibaba.xxpt.gateway.shared.api.request.OapiOpenplatformMessageRemoveCallbackFailedRequest;
import com.alibaba.xxpt.gateway.shared.api.request.OapiOpenplatformMessageRetryCallbackFailedRequest;
import com.alibaba.xxpt.gateway.shared.api.request.OapiOpenplatformMessageUpdateEventCallbackDefineRequest;
import com.alibaba.xxpt.gateway.shared.api.response.OapiMoziEmployeeListEmployeePositionsByEmployeeCodeResponse;
import com.alibaba.xxpt.gateway.shared.api.response.OapiMoziEmployeeListEmployeesByCodesResponse;
import com.alibaba.xxpt.gateway.shared.api.response.OapiMoziOrganizationPageOrganizationEmployeeCodesResponse;
import com.alibaba.xxpt.gateway.shared.api.response.OapiOpenplatformMessageDeleteEventCallbackDefineResponse;
import com.alibaba.xxpt.gateway.shared.api.response.OapiOpenplatformMessageQueryCallbackDefineResponse;
import com.alibaba.xxpt.gateway.shared.api.response.OapiOpenplatformMessageQueryCallbackFailedResponse;
import com.alibaba.xxpt.gateway.shared.api.response.OapiOpenplatformMessageRegisterEventCallbackResponse;
import com.alibaba.xxpt.gateway.shared.api.response.OapiOpenplatformMessageRemoveCallbackFailedResponse;
import com.alibaba.xxpt.gateway.shared.api.response.OapiOpenplatformMessageRetryCallbackFailedResponse;
import com.alibaba.xxpt.gateway.shared.api.response.OapiOpenplatformMessageUpdateEventCallbackDefineResponse;
import com.alibaba.xxpt.gateway.shared.client.http.ExecutableClient;
import com.alibaba.xxpt.gateway.shared.client.http.IntelligentGetClient;
import com.alibaba.xxpt.gateway.shared.client.http.PostClient;
import com.alibaba.xxpt.gateway.shared.client.http.api.OapiSpResultContent;
import com.authine.cloudpivot.ext.domain.OrgDepartment;
import com.authine.cloudpivot.ext.domain.OrgDeptUser;
import com.authine.cloudpivot.ext.domain.OrgRoleUser;
import com.authine.cloudpivot.ext.domain.OrgUser;
import com.authine.cloudpivot.ext.service.SyncOrgSevice;
import com.authine.cloudpivot.util.ApiClient;
import com.authine.cloudpivot.util.StringUtil;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Headers;

@Slf4j
@Service
public class SyncOrgServiceImpl implements SyncOrgSevice {

    @Resource
    private OrgUserMapper orgUserMapper;

    @Resource
    private OrgDeptUserMapper orgDeptUserMapper;

    @Resource
    private OrgRoleUserMapper orgRoleUserMapper;

    @Resource
    private OrgDepartmentMapper orgDepartmentMapper;

    @Resource
    private HOrgDepartmentMapper hOrgDepartmentMapper;

    /*
    @Resource
    private DataSourceTransactionManager dataSourceTransactionManager;

    @Resource
    private TransactionDefinition transactionDefinition;

    private TransactionStatus transactionStatus = null;
    */

    @Value("${syncorg.topDepartmentId}")
    private String topDepartmentId;

    @Value("${syncorg.domainName}")
    private String domainName;

    @Value("${syncorg.protocal}")
    private String protocal;

    @Value("${syncorg.appKey}")
    private String appKey;

    @Value("${syncorg.appSecret}")
    private String appSecret;

    @Value("${syncorg.tenantId}")
    private String tenantId;

    @Value("${syncorg.pageSize}")
    private Integer pageSize;

    @Value("${yunshu.engine.server}")
    private String yunshuEngineServer;

    @Value("${syncorg.retryLimitSeconds}")
    private long retryLimitSeconds;

    @Value("${syncorg.deleteRoleUserBeforeSync}")
    private boolean deleteRoleUserBeforeSync;

    private static String corpId = "main";

    private static ExecutableClient executableClient;

    /**
     * 全量同步
     *
     * @param userId
     *            当前登录的用户ID
     * @return 返回map，flag=是否成功，msg=错误信息
     */
    @Override
    public Map<String, Object> syncOrgAll(String userId) {

        log.info("当前API={{domainName={}, appKey={}, appSecret={}}}", domainName, appKey, appSecret);

        if (!StringUtils.isEmpty(topDepartmentId)) {
            OrgDepartment orgDepartment = orgDepartmentMapper.selectOneByPrimaryKey(topDepartmentId);
            if (orgDepartment != null) {
                corpId = orgDepartment.getCorpId();
            }
        }

        Map<String, Object> result = new HashMap<>();
        String msg;

        try {
            Date date = new Date();
            // 获取根组织
            List<OrgDepartment> orgDepartmentList = getTopOrgDepartmentList();
            for (OrgDepartment orgDepartment : orgDepartmentList) {
                orgDepartment.setSourceId(orgDepartment.getId());
                orgDepartment.setCreater(userId);
                orgDepartment.setModifier(userId);
                // orgDepartment.setExtend1("AutoAddUser:true");
                // orgDepartment.setExtend2("CreateDeptGroup:true");
                // orgDepartment.setExtend3(date.toString());
                orgDepartment.setCreatedTime(date);
                orgDepartment.setModifiedTime(date);
                orgDepartment.setLeaf(false);
                orgDepartment.setIsShow(true);
                orgDepartment.setDeptType("YUNS_DEPT");
                orgDepartment.setCorpId(corpId);
                // 如果数据库存在，则更新，不存在则新增
                OrgDepartment tOrgDept = orgDepartmentMapper.selectOneByPrimaryKey(orgDepartment.getId());
                if (tOrgDept == null) {
                    orgDepartmentMapper.insertByDepartment(orgDepartment);
                } else {
                    orgDepartmentMapper.updateByDepartment(orgDepartment);
                }
            }
            OrgDepartment topOrgDepartment = orgDepartmentList.get(0);
            // 清理待更新组织的数据
            // deleteData(topOrgDepartment.getId());
            // 同步部门
            // orgDepartmentList.addAll(getAllChildrenOrg(topOrgDepartment.getId(), new ArrayList<>()));
            // syncDept(userId, date, topOrgDepartment.getId(), orgDepartmentList);
            syncOgDepartment(userId, date, topOrgDepartment.getId());
            // 更新部门的叶子节点
            updateDepartmentLeaf();
            // 处理部门表QueryCode
            updateQueryCode();
            // 同步用户
            syncUserByOrgDepartmentId(userId, topOrgDepartment.getId(), date);
            // 绑定admin的corpId
            updateAdminCorpId();
            // 清空引擎缓存
            cleanCache();

            executableClient.destroy();
            msg = "组织机构全量同步成功！";
            result.put("status", true);
            result.put("msg", msg);
            return result;
        } catch (Exception e) {
            /*try {
                dataSourceTransactionManager.rollback(transactionStatus);
            } catch (Exception e1) {
                log.error(e1.getMessage());
            }*/
            e.printStackTrace();
            msg = "同步组织架构出错：" + e.getMessage();
            log.error(msg);
            log.info("当前API={{domainName={}, appKey={}, appSecret={}}}", domainName, appKey, appSecret);

            result.put("status", false);
            result.put("msg", msg);
            return result;
        } finally {
            if (executableClient != null) {
                executableClient.destroy();
            }
        }

    }

    /**
     * 增量同步
     *
     * @param userId
     *            当前登录的用户ID
     * @return 返回map，flag=是否成功，msg=错误信息
     */
    @Override
    public Map<String, Object> syncOrgIncrement(String userId, String deptartmentId) {
        log.info("当前deptartmentId={}, API={{domainName={}, appKey={}, appSecret={}}}", deptartmentId, domainName,
            appKey, appSecret);

        // 获取根节点的corpId，如果没有则为main
        if (!StringUtils.isEmpty(topDepartmentId)) {
            OrgDepartment orgDepartment = orgDepartmentMapper.selectOneByPrimaryKey(topDepartmentId);
            if (orgDepartment != null) {
                corpId = orgDepartment.getCorpId();
            }
        }
        Map<String, Object> result = new HashMap<>();
        String msg;
        try {
            Date date = new Date();
            // 清理待更新组织的数据
            deleteData(deptartmentId);
            // 同步部门
            List<OrgDepartment> orgDepartmentList = getAllChildrenOrg(deptartmentId, new ArrayList<>());
            if (orgDepartmentList.size() > 0) {
                // 同步部门
                syncDept(userId, date, deptartmentId, orgDepartmentList);
                // 更新部门的叶子节点
                updateDepartmentLeaf();
                // 处理部门表QueryCode
                updateQueryCode();
            }
            // 同步用户
            syncUserByOrgDepartmentId(userId, deptartmentId, date);
            // 绑定admin的corpId
            updateAdminCorpId();
            // 清空引擎缓存
            cleanCache();

            executableClient.destroy();
            msg = "组织机构增量量同步成功！";
            result.put("status", true);
            result.put("msg", msg);
            return result;
        } catch (Exception e) {
            /*try {
                dataSourceTransactionManager.rollback(transactionStatus);
            } catch (Exception e1) {
                log.error(e1.getMessage());
            }*/
            e.printStackTrace();
            msg = "同步组织架构出错：" + e.getMessage();
            log.error(msg);
            log.info("当前deptartmentId={}, API={{domainName={}, appKey={}, appSecret={}}}", deptartmentId, domainName,
                appKey, appSecret);

            result.put("status", false);
            result.put("msg", msg);
            return result;
        } finally {
            if (executableClient != null) {
                executableClient.destroy();
            }
        }
    }

    @Override
    public Map<String, Object> syncUsers(String userId, String deptartmentId) {
        Map<String, Object> result = new HashMap<>();
        String msg;
        try {
            if (StringUtils.isEmpty(deptartmentId)) {
                List<OrgDepartment> orgDepartments = orgDepartmentMapper.selectAll();
                for (OrgDepartment depart : orgDepartments) {
                    syncUserByOrgDepartmentId(userId, depart.getId(), new Date());
                }
            } else {
                syncUserByOrgDepartmentId(userId, deptartmentId, new Date());
            }
            // 清空引擎缓存
            cleanCache();
            executableClient.destroy();
            msg = "同步用户成功！";
            result.put("status", true);
            result.put("msg", msg);
        } catch (Exception e) {
            e.printStackTrace();
            msg = "同步用户失败：" + e.getMessage();
            result.put("status", false);
            result.put("msg", msg);
            log.error(msg);
        }
        return result;
    }

    // 同步部门表
    private void syncDept(String userId, Date date, String deptartmentId, List<OrgDepartment> orgDepartmentList) {
        log.info("syncDept start>>>");
        log.debug("deptartmentId={}", deptartmentId);
        // transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);

        Set<String> idSet = getAllChildrenDepartmentIdByDepartmentId(deptartmentId, new HashSet<>());
        for (OrgDepartment orgDepartment : orgDepartmentList) {
            idSet.remove(orgDepartment.getId());
        }
        if (idSet.size() > 0) {
            orgDepartmentMapper.deleteLogicByIdSet(idSet);
            orgUserMapper.deleteLogicByDepartmentIdSet(idSet);
            orgDeptUserMapper.deleteByDeptIdSet(idSet);
            if (deleteRoleUserBeforeSync) {
                orgRoleUserMapper.deleteByDeptIdSet(idSet);
            }
        }
        // 部门的唯一标识号最为id
        List<OrgDepartment> tOrgDepartmentList = orgDepartmentMapper.selectByPrimaryKeyList(orgDepartmentList);
        List<String> idList = new ArrayList<>();
        for (OrgDepartment orgDepartment : tOrgDepartmentList) {
            idList.add(orgDepartment.getId());
        }
        List<OrgDepartment> updateList = new ArrayList<>();
        List<OrgDepartment> insertList = new ArrayList<>();
        for (OrgDepartment orgDepartment : orgDepartmentList) {
            orgDepartment.setSourceId(orgDepartment.getId());
            orgDepartment.setCreater(userId);
            orgDepartment.setModifier(userId);
            // orgDepartment.setExtend1("AutoAddUser:true");
            // orgDepartment.setExtend2("CreateDeptGroup:true");
            orgDepartment.setExtend3(date.toString());
            orgDepartment.setCreatedTime(date);
            orgDepartment.setModifiedTime(date);
            orgDepartment.setLeaf(false);
            orgDepartment.setIsShow(true);
            orgDepartment.setDeptType("YUNS_DEPT");
            orgDepartment.setCorpId(corpId);
            // 如果数据库存在，则更新，不存在则新增
            /* OrgDepartment tOrgDept = orgDepartmentMapper.selectOneByPrimaryKey(orgDepartment.getId());
            if (tOrgDept == null) {
                orgDepartmentMapper.insertByDepartment(orgDepartment);
            } else {
                orgDepartmentMapper.updateByDepartment(orgDepartment);
            }*/
            if (idList.contains(orgDepartment.getId())) {
                updateList.add(orgDepartment);
            } else {
                insertList.add(orgDepartment);
            }
        }
        if (updateList.size() > 0) {
            int size = 1000;
            int loop = updateList.size() % size == 0 ? updateList.size() / size : updateList.size() / size + 1;
            for (int i = 0; i < loop; i++) {
                if (i == loop - 1) {
                    orgDepartmentMapper.updateByDepartmentList(updateList.subList(i * size, updateList.size()));
                } else {
                    orgDepartmentMapper.updateByDepartmentList(updateList.subList(i * size, i * size + size));
                }
            }
        }
        if (insertList.size() > 0) {
            int size = 1000;
            int loop = insertList.size() % size == 0 ? insertList.size() / size : insertList.size() / size + 1;
            for (int i = 0; i < loop; i++) {
                if (i == loop - 1) {
                    orgDepartmentMapper.insertByDepartmentList(insertList.subList(i * size, insertList.size()));
                } else {
                    orgDepartmentMapper.insertByDepartmentList(insertList.subList(i * size, i * size + size));
                }
            }
        }
        // dataSourceTransactionManager.commit(transactionStatus);

        log.info("<<<syncDept end");
    }

    // 从数据库根据部门ID获取所有子ID
    private Set<String> getAllChildrenDepartmentIdByDepartmentId(String departmentId, Set<String> result) {
        log.info("getAllChildrenDepartmentIdByDepartmentId start >>>");
        log.debug("departmentId={}", departmentId);
        Set<String> tmpSet = orgDepartmentMapper.selectByParentId(departmentId);
        result.addAll(tmpSet);
        for (String str : tmpSet) {
            result.addAll(getAllChildrenDepartmentIdByDepartmentId(str, result));
        }
        log.info("<<< getAllChildrenDepartmentIdByDepartmentId end");
        return result;
    }

    // 同步用户表，用户部门映射表，角色表，用户角色表
    private void syncUser(String userId, Date date, List<OrgUser> orgUserList) {
        log.info("syncUser start>>>");

        /*
        List<OrgUser> updateOrgUserList = new ArrayList<>();
        List<OrgUser> insertOrgUserList = new ArrayList<>();
        List<OrgDeptUser> insertOrgDeptUserList = new ArrayList<>();
        List<OrgRoleUser> insertOrgRoleUserList = new ArrayList<>();
        */
        Set<String> deleteUserIdSet = new HashSet<>();

        for (OrgUser orgUser : orgUserList) {
            // 部分字段设置默认值
            orgUser.setId(StringUtil.getUUID());
            orgUser.setCreater(userId);
            orgUser.setCreatedTime(date);
            orgUser.setModifier(userId);
            orgUser.setModifiedTime(date);
            orgUser.setActive(true);
            orgUser.setAdmin(false);
            orgUser.setGender("OTHER");
            orgUser.setLeader(false);
            // 默认密码123456
            orgUser.setPassword("{bcrypt}$2a$10$fnuUuxqxL/DojH5MGLBINOmjNDtmSVVCI8OFlbvWG1ZAj0oWpSoDS");
            // orgUser.setUsername(orgUser.getUserId());
            orgUser.setDeleted(false);
            orgUser.setExtend2("jobNumber:");
            orgUser.setEnabled(true);
            orgUser.setCorpId(corpId);
            orgUser.setPinYin(orgUser.getName() == null ? null : StringUtil.getPinyinLowCase(orgUser.getName()));
            orgUser.setShortPinYin(
                orgUser.getName() == null ? null : StringUtil.getPinYinHeadCharLowCase(orgUser.getName()));

            String[] departmentIds = orgUser.getDepartmentId().split(",");
            orgUser.setDepartmentId(departmentIds[0]);
            String[] roles = orgUser.getExtend1().split(",");
            orgUser.setExtend1(null);

            String orgDeptUserId = "";
            List<OrgUser> tOrgUserList = orgUserMapper.selectByUserId(orgUser);
            if (tOrgUserList != null && tOrgUserList.size() > 0) {
                orgDeptUserId = tOrgUserList.get(0).getId();
                orgUserMapper.updateByUser(orgUser);
                // updateOrgUserList.add(orgUser);
            } else {
                orgUserMapper.insertByUser(orgUser);
                // insertOrgUserList.add(orgUser);
            }
            for (int i = 0; i < departmentIds.length; i++) {
                // 获取用户和部门关系
                if ("ENABLE".equals(orgUser.getStatus())) {
                    OrgDeptUser orgDeptUser = new OrgDeptUser();
                    orgDeptUser.setId(StringUtil.getUUID());
                    if ("".equals(orgDeptUserId)) {
                        orgDeptUser.setUserId(orgUser.getId());
                    } else {
                        orgDeptUser.setUserId(orgDeptUserId);
                    }
                    orgDeptUser.setCreater(userId);
                    orgDeptUser.setCreatedTime(date);
                    orgDeptUser.setModifier(userId);
                    orgDeptUser.setModifiedTime(date);
                    orgDeptUser.setExtend3(orgUser.getExtend3());
                    orgDeptUser.setDeleted(false);
                    orgDeptUser.setDeptId(departmentIds[i]);
                    orgDeptUser.setMain(false);
                    orgDeptUserMapper.insertByDeptUser(orgDeptUser);
                    // insertOrgDeptUserList.add(orgDeptUser);
                } else {
                    deleteUserIdSet.add(orgUser.getUserId());
                }

                // 获取用户和角色关系
                if ("ENABLE".equals(orgUser.getStatus()) && !StringUtils.isEmpty(roles[i])) {
                    OrgRoleUser orgRoleUser = new OrgRoleUser();
                    orgRoleUser.setId(StringUtil.getUUID());
                    if ("".equals(orgDeptUserId)) {
                        orgRoleUser.setUserId(orgUser.getId());
                    } else {
                        orgRoleUser.setUserId(orgDeptUserId);
                    }
                    orgRoleUser.setCreater(userId);
                    orgRoleUser.setCreatedTime(date);
                    orgRoleUser.setModifier(userId);
                    orgRoleUser.setModifiedTime(date);
                    orgRoleUser.setExtend3(orgUser.getExtend3());
                    orgRoleUser.setDeleted(false);
                    orgRoleUser.setRoleId(roles[i]);
                    orgRoleUser.setUnitType("USER");
                    orgRoleUserMapper.insertByRoleUser(orgRoleUser);
                    // insertOrgRoleUserList.add(orgRoleUser);
                }
            }
        }
        /*
        // transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        if (updateOrgUserList.size() > 0) {
            int size = 1000;
            int loop = updateOrgUserList.size() % size == 0 ? updateOrgUserList.size() / size : updateOrgUserList.size() / size + 1;
            for (int i = 0; i < loop; i++) {
                if (i == loop - 1) {
                    orgUserMapper.updateByUserList(updateOrgUserList.subList(i * size, updateOrgUserList.size()));
                } else {
                    orgUserMapper.updateByUserList(updateOrgUserList.subList(i * size, i * size + size));
                }
            }
        }
        if (insertOrgUserList.size() > 0) {
            int size = 1000;
            int loop = insertOrgUserList.size() % size == 0 ? insertOrgUserList.size() / size : insertOrgUserList.size() / size + 1;
            for (int i = 0; i < loop; i++) {
                if (i == loop - 1) {
                    orgUserMapper.insertByUserList(insertOrgUserList.subList(i * size, insertOrgUserList.size()));
                } else {
                    orgUserMapper.insertByUserList(insertOrgUserList.subList(i * size, i * size + size));
                }
            }
        }
        if (insertOrgDeptUserList.size() > 0) {
            int size = 1000;
            int loop = insertOrgDeptUserList.size() % size == 0 ? insertOrgDeptUserList.size() / size : insertOrgDeptUserList.size() / size + 1;
            for (int i = 0; i < loop; i++) {
                if (i == loop - 1) {
                    orgDeptUserMapper.insertByDeptUserList(insertOrgDeptUserList.subList(i * size, insertOrgDeptUserList.size()));
                } else {
                    orgDeptUserMapper.insertByDeptUserList(insertOrgDeptUserList.subList(i * size, i * size + size));
                }
            }
        }
        if (insertOrgRoleUserList.size() > 0) {
            int size = 1000;
            int loop = insertOrgRoleUserList.size() % size == 0 ? insertOrgRoleUserList.size() / size : insertOrgRoleUserList.size() / size + 1;
            for (int i = 0; i < loop; i++) {
                if (i == loop - 1) {
                    orgRoleUserMapper.insertByRoleUserList(insertOrgRoleUserList.subList(i * size, insertOrgRoleUserList.size()));
                } else {
                    orgRoleUserMapper.insertByRoleUserList(insertOrgRoleUserList.subList(i * size, i * size + size));
                }
            }
        }
        */
        if (deleteUserIdSet.size() > 0) {
            orgDeptUserMapper.deleteByDeptIdSet(deleteUserIdSet);
            orgRoleUserMapper.deleteByDeptIdSet(deleteUserIdSet);
        }

        // dataSourceTransactionManager.commit(transactionStatus);

        log.info("<<<syncUser end");
    }

    private void deleteData(String orgDepartmentId) {
        // 先标记该部门下都为删除，后面再更新
        orgUserMapper.deleteLogicByDepartmentId(orgDepartmentId);
        // 删除该部门下用户的关系
        orgDeptUserMapper.deleteByDeptId(orgDepartmentId);
        // 删除该部门下用户对应的角色关系
        if (deleteRoleUserBeforeSync) {
            orgRoleUserMapper.deleteByDeptId(orgDepartmentId);
        }
        List<OrgDepartment> allChildrenOrg = getAllChildrenOrg(orgDepartmentId, new ArrayList<>());
        for (OrgDepartment orgDepartment : allChildrenOrg) {
            // 先标记该部门下都为删除，后面再更新
            orgUserMapper.deleteLogicByDepartmentId(orgDepartment.getId());
            // 删除该部门下用户的关系
            orgDeptUserMapper.deleteByDeptId(orgDepartment.getId());
            // 删除该部门下用户对应的角色关系
            if (deleteRoleUserBeforeSync) {
                orgRoleUserMapper.deleteByDeptId(orgDepartmentId);
            }
        }
    }

    // 处理部门表QueryCode
    @Override
    public void updateQueryCode() {
        log.info("处理部门表QueryCode开始>>>");
        List<OrgDepartment> deptAllList = orgDepartmentMapper.selectAll();
        StringBuilder sb = new StringBuilder();
        for (OrgDepartment dept : deptAllList) {
            if (StringUtils.isEmpty(dept.getParentId())) {
                dept.setQueryCode(dept.getSourceId());
            } else {
                // 当前部门SourceId
                sb.delete(0, sb.length());
                sb.append(dept.getSourceId());
                // 部门的父id
                String deptId = dept.getParentId();
                while (!StringUtils.isEmpty(deptId)) {
                    OrgDepartment orgDept = orgDepartmentMapper.selectOneByPrimaryKey(deptId);
                    if (null == orgDept) {
                        break;
                    }
                    sb.insert(0, "#").insert(0, orgDept.getSourceId());
                    if (!StringUtils.isEmpty(orgDept.getParentId())) {
                        deptId = orgDept.getParentId();
                    } else {
                        deptId = "";
                    }
                }
                dept.setQueryCode(sb.toString());
            }
            orgDepartmentMapper.updateQueryCode(dept);
        }
        log.info("<<<处理部门表QueryCode结束");
    }

    // 处理部门表QueryCodeV2
    @Override
    public void updateQueryCodeV2() {
        log.info("处理部门表QueryCodeV2开始>>>");
        List<OrgDepartment> deptAllList = orgDepartmentMapper.selectAll();

        StringBuilder sb = new StringBuilder();
        for (OrgDepartment dept : deptAllList) {
            if (StringUtils.isEmpty(dept.getParentId())) {
                dept.setQueryCode(dept.getSourceId());
            } else {
                sb.delete(0, sb.length());
                if ("village".equals(dept.getExtend3())) {
                    String headerNum = orgDepartmentMapper.selectHeaderNumForVillageById(dept.getId());
                    sb.append(headerNum);
                } else {
                    sb.append(dept.getSourceId());
                }
                // 部门的父id
                String deptId = dept.getParentId();
                while (!StringUtils.isEmpty(deptId)) {
                    OrgDepartment orgDept = orgDepartmentMapper.selectOneByPrimaryKey(deptId);
                    if (null == orgDept) {
                        break;
                    }
                    sb.insert(0, "#").insert(0, orgDept.getSourceId());
                    if (!StringUtils.isEmpty(orgDept.getParentId())) {
                        deptId = orgDept.getParentId();
                    } else {
                        deptId = "";
                    }
                }
                dept.setQueryCode(sb.toString());
            }
            orgDepartmentMapper.updateQueryCode(dept);
        }
        deptAllList = new ArrayList<>();

        List<OrgDepartment> deptLikeList = orgDepartmentMapper.selectLikeQueryCode("#1#");
        int lastSize = 0;
        while (deptLikeList != null && deptLikeList.size() > 0) {
            lastSize = deptLikeList.size();
            for (OrgDepartment dept : deptLikeList) {
                sb.delete(0, sb.length());
                sb.append(dept.getSourceId());
                // 部门的父id
                String deptId = dept.getParentId();
                while (!StringUtils.isEmpty(deptId)) {
                    OrgDepartment orgDept = orgDepartmentMapper.selectOneByPrimaryKey(deptId);
                    if (null == orgDept) {
                        break;
                    }
                    if ("village".equals(orgDept.getExtend3())) {
                        sb.insert(0, "#").insert(0, orgDept.getQueryCode());
                        break;
                    } else {
                        sb.insert(0, "#").insert(0, orgDept.getSourceId());
                    }
                    if (!StringUtils.isEmpty(orgDept.getParentId())) {
                        deptId = orgDept.getParentId();
                    } else {
                        deptId = "";
                    }
                }
                dept.setQueryCode(sb.toString());
                orgDepartmentMapper.updateQueryCode(dept);
            }
            deptLikeList = orgDepartmentMapper.selectLikeQueryCode("#1#");
            if (deptLikeList != null && deptLikeList.size() > 0 && lastSize == deptLikeList.size()) {
                StringBuilder ids = new StringBuilder();
                for (OrgDepartment department : deptLikeList) {
                    ids.append(department.getId()).append(",");
                }
                log.error("更新queryCode失败，不允许村级下有村，请检查一下数据是否正常{}", ids);
                throw new RuntimeException("更新queryCode失败，不允许村级下有村，请检查一下数据是否正常{" + ids + "}");
            }
        }

        log.info("<<<处理部门表QueryCodeV2结束");
    }




    // 处理部门表QueryCodeV3
    @Override
    public void updateQueryCodeV3(String rootDeptId) {
        log.info("处理部门表QueryCodeV3开始>>>");
        List<String> ids = new ArrayList<>();
        // 保存数据
        List<String> deptIds = getDeptIds(rootDeptId, ids);
        StringBuilder sb = new StringBuilder();
        for (String id : deptIds) {
            OrgDepartment dept = orgDepartmentMapper.selectByPrimaryKey(id);
            if(dept == null){
                continue;
            }
            if (StringUtils.isEmpty(dept.getParentId())) {
                dept.setQueryCode(dept.getSourceId());
            } else {
                sb.delete(0, sb.length());
                if ("village".equals(dept.getExtend3())) {
                    String headerNum = orgDepartmentMapper.selectHeaderNumForVillageById(dept.getId());
                    sb.append(headerNum);
                } else {
                    sb.append(dept.getSourceId());
                }
                // 部门的父id
                String deptId = dept.getParentId();
                while (!StringUtils.isEmpty(deptId)) {
                    OrgDepartment orgDept = orgDepartmentMapper.selectOneByPrimaryKey(deptId);
                    if (null == orgDept) {
                        break;
                    }
                    sb.insert(0, "#").insert(0, orgDept.getSourceId());
                    if (!StringUtils.isEmpty(orgDept.getParentId())) {
                        deptId = orgDept.getParentId();
                    } else {
                        deptId = "";
                    }
                }
                dept.setQueryCode(sb.toString());
            }
            orgDepartmentMapper.updateQueryCode(dept);
        }
        log.info("<<<处理部门表QueryCodeV3结束");
    }


    /**
     * @param id
     * @param list
     * @return java.util.List<java.lang.String>
     * @author liujing
     * @description: 递归获取部门最底层部门id集合
     * @date 2021/6/17
     */
    public List<String> getDeptIds(String id, List<String> list) {
        List<String> list1 = hOrgDepartmentMapper.getSonDeptIds(id);
        if (CollectionUtils.isEmpty(list1)) {
            list.add(id);
        } else {
            for (String s : list1) {
                getDeptIds(s, list);
            }
        }
        return list;
    }

    // 绑定admin的corpId
    private void updateAdminCorpId() {
        // transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        orgUserMapper.updateAdminCorpId();
        // dataSourceTransactionManager.commit(transactionStatus);
    }

    // 更新叶子节点
    private void updateDepartmentLeaf() {
        log.info("更新叶子节点开始>>>");
        // transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        orgDepartmentMapper.updateResetLeaf();
        orgDepartmentMapper.updateLeaf();
        orgDepartmentMapper.updateRootDepartmentLeaf();
        // dataSourceTransactionManager.commit(transactionStatus);
        log.info("<<<更新叶子节点结束");
    }

    // 清空引擎缓存
    private void cleanCache() throws IOException {
        if (StringUtils.isEmpty(yunshuEngineServer)) {
            log.error("application-syncorg.yml/yunshu.engine.server配置错误。当前值为空");
        } else if (!yunshuEngineServer.toLowerCase().startsWith("http")) {
            log.error("application-syncorg.yml/yunshu.engine.server配置错误。当前值为{}", yunshuEngineServer);
        } else {
            yunshuEngineServer = yunshuEngineServer.endsWith("/")
                ? yunshuEngineServer.substring(0, yunshuEngineServer.length() - 1) : yunshuEngineServer;
        }
        ApiClient apiClient = new ApiClient(false);
        String accessToken = apiClient.post(yunshuEngineServer
            + "/oauth/token?grant_type=client_credentials&client_id=xclient&client_secret=0a417ecce58c31b32364ce19ca8fcd15",
            (Headers)null, null, null);
        JsonObject object = new JsonParser().parse(accessToken).getAsJsonObject();
        String r = apiClient.get(yunshuEngineServer + "/api/v1/organization/cleanAllUserCache",
            Headers.of("access_token", object.get("access_token").getAsString()), null);
        log.info("用户缓存清除成功{}", r);
        r = apiClient.get(yunshuEngineServer + "/api/v1/organization/cleanAllDepartmentCache",
            Headers.of("access_token", object.get("access_token").getAsString()), null);
        log.info("部门缓存清除成功{}", r);
    }

    @SuppressWarnings("static-access")
    private ExecutableClient getExecutableClient() {
        if (this.executableClient == null) {
            this.executableClient = ExecutableClient.getInstance();
            // DomainName不同环境对应不同域名，示例为sass域名
            this.executableClient.setDomainName(domainName);
            this.executableClient.setProtocal(protocal);
            // 应用App Key
            this.executableClient.setAccessKey(appKey);
            // 应用App Secret
            this.executableClient.setSecretKey(appSecret);
            this.executableClient.init();
        }
        return this.executableClient;
    }

    // 根据ID获取下级所有机构的信息
    private List<OrgDepartment> getAllChildrenOrg(String orgDepartmentId, List<OrgDepartment> orgDepartmentList) {
        List<OrgDepartment> orgDepartmentByParent = getOrgDepartmentByParent(orgDepartmentId);
        orgDepartmentList.addAll(orgDepartmentByParent);
        for (OrgDepartment orgDeptment : orgDepartmentByParent) {
            getAllChildrenOrg(orgDeptment.getId(), orgDepartmentList);
        }
        return orgDepartmentList;
    }

    private void syncOgDepartment(String userId, Date date, String orgDepartmentId) {
        List<OrgDepartment> orgDepartmentByParent = getOrgDepartmentByParent(orgDepartmentId);
        if (orgDepartmentByParent != null && orgDepartmentByParent.size() > 0) {
            syncDept(userId, date, orgDepartmentId, orgDepartmentByParent);
        }
        for (OrgDepartment orgDeptment : orgDepartmentByParent) {
            syncOgDepartment(userId, date, orgDeptment.getId());
        }
    }

    // 获取当前应用顶层机构
    private List<OrgDepartment> getTopOrgDepartmentList() {
        List<OrgDepartment> result = new ArrayList<>();
        String api = "/auth/scopesV2";
        PostClient postClient;
        // 调用API
        String apiResult = "";
        long startTime = System.currentTimeMillis();
        boolean success = false;
        JSONObject jsonObject = null;
        while (!success) {
            try {
                postClient = getExecutableClient().newPostClient(api);
                // 设置参数
                postClient.addParameter("tenantId", tenantId);
                apiResult = postClient.post();
                jsonObject = JSONObject.parseObject(apiResult);
                log.debug(jsonObject.toJSONString());
                success = jsonObject.getBooleanValue("success");
                log.debug("success=" + success);
            } catch (Exception e) {
                log.debug(e.getMessage());
            }
            if ((System.currentTimeMillis() - startTime) / 1000 > retryLimitSeconds) {
                if (jsonObject != null) {
                    log.error(jsonObject.toJSONString());
                }
                log.error("调用api已超过{}秒，终止同步操作！", retryLimitSeconds);
                return null;
            }
        }
        if (success) {
            JSONArray deptVisibleScopes = jsonObject.getJSONObject("content").getJSONArray("deptVisibleScopes");
            if (deptVisibleScopes != null) {
                for (int i = 0; i < deptVisibleScopes.size(); i++) {
                    OrgDepartment orgDepartment = new OrgDepartment();
                    orgDepartment.setId(deptVisibleScopes.get(i).toString());
                    if (StringUtils.isEmpty(topDepartmentId)) {
                        List<OrgDepartment> orgDepartments = orgDepartmentMapper.selectTopDept();
                        if (orgDepartments.size() > 0) {
                            orgDepartment.setParentId(orgDepartments.get(0).getId());
                            orgDepartment
                                .setQueryCode(orgDepartments.get(0).getQueryCode() + "#" + orgDepartment.getId());
                        }
                    } else {
                        orgDepartment.setParentId(topDepartmentId);
                        OrgDepartment orgDepartment1 = orgDepartmentMapper.selectOneByPrimaryKey(topDepartmentId);
                        orgDepartment.setQueryCode(orgDepartment1.getQueryCode() + "#" + orgDepartment.getId());
                    }
                    updateOrgDepartmentDetails(orgDepartment);
                    result.add(orgDepartment);
                }
            }
        } else {
            log.info("请求API异常,{}", jsonObject.getString("errorMsg"));
        }
        return result;
    }

    // 根据父ID获取下一级机构
    private List<OrgDepartment> getOrgDepartmentByParent(String orgDepartmentId) {
        List<OrgDepartment> result = new ArrayList<>();
        String api = "/mozi/organization/pageSubOrganizationCodes";
        PostClient postClient = getExecutableClient().newPostClient(api);
        // 设置参数
        postClient.addParameter("returnTotalSize", "true");
        postClient.addParameter("pageSize", pageSize + "");
        postClient.addParameter("organizationCode", orgDepartmentId);
        postClient.addParameter("pageNo", "1");
        postClient.addParameter("status", "TOTAL");
        postClient.addParameter("tenantId", tenantId);
        String apiResult = postClient.post();
        JSONObject jsonObject = JSONObject.parseObject(apiResult);
        boolean success = jsonObject.getBooleanValue("success");
        // 调用API
        if (success) {
            OrgDepartment tOrgDepartment = orgDepartmentMapper.selectOneByPrimaryKey(orgDepartmentId);
            Integer totalSize = jsonObject.getJSONObject("content").getInteger("totalSize");
            Integer pageCount = totalSize % pageSize == 0 ? totalSize / pageSize : totalSize / pageSize + 1;
            for (int i = 1; i <= pageCount; i++) {
                postClient = getExecutableClient().newPostClient(api);
                // 设置参数
                postClient.addParameter("returnTotalSize", "true");
                postClient.addParameter("pageSize", pageSize + "");
                postClient.addParameter("organizationCode", orgDepartmentId);
                postClient.addParameter("pageNo", i + "");
                postClient.addParameter("status", "TOTAL");
                postClient.addParameter("tenantId", tenantId);
                // 调用API
                apiResult = postClient.post();
                jsonObject = JSONObject.parseObject(apiResult);
                log.debug(jsonObject.toJSONString());
                success = jsonObject.getBooleanValue("success");
                if (success) {
                    JSONArray depts = jsonObject.getJSONObject("content").getJSONArray("data");
                    if (depts != null) {
                        for (Object dept : depts) {
                            OrgDepartment orgDepartment = new OrgDepartment();
                            orgDepartment.setId(dept.toString());
                            orgDepartment.setParentId(orgDepartmentId);
                            if (tOrgDepartment != null) {
                                orgDepartment.setQueryCode(tOrgDepartment.getQueryCode() + "#" + orgDepartment.getId());
                            }
                            updateOrgDepartmentDetails(orgDepartment);
                            result.add(orgDepartment);
                        }
                    }
                } else {
                    log.info("请求API异常,{}", jsonObject.getString("errorMsg"));
                }
            }
        } else {
            log.info("请求API异常,{}", jsonObject.getString("errorMsg"));
        }
        return result;
    }

    // 更新部门信息
    private void updateOrgDepartmentDetails(OrgDepartment orgDepartment) {
        String api = "/mozi/organization/getOrganizationByCode";
        PostClient postClient = getExecutableClient().newPostClient(api);
        // 设置参数
        postClient.addParameter("organizationCode", orgDepartment.getId());
        postClient.addParameter("tenantId", tenantId);
        // 调用API
        String apiResult = postClient.post();
        JSONObject jsonObject = JSONObject.parseObject(apiResult);
        boolean success = jsonObject.getBooleanValue("success");
        if (success) {
            JSONObject dept = jsonObject.getJSONObject("content").getJSONObject("data");
            if (dept != null) {
                orgDepartment.setSortKey(dept.getLong("displayOrder"));
                orgDepartment.setName(dept.getString("organizationName"));
                orgDepartment.setLeaf(dept.getBooleanValue("leaf"));
                orgDepartment.setModifiedTime(dept.getDate("gmtCreate"));
                if ("A".equals(dept.getString("status"))) {
                    orgDepartment.setDeleted(false);
                    orgDepartment.setEnabled(true);
                } else {
                    orgDepartment.setDeleted(true);
                    orgDepartment.setEnabled(false);
                }
            } else {
                log.error("浙政钉中不存在该部门ID={}，可能已被删除，请尝试同步上级组织。", orgDepartment.getId());
                throw new RuntimeException("浙政钉中不存在该部门ID={" + orgDepartment.getId() + "}，可能已被删除，请尝试同步上级组织。");
            }
        } else {
            log.info("请求API异常,{}", jsonObject.getString("errorMsg"));
        }
    }

    // 获取指定部门下的所有用户
    @SuppressWarnings("unused")
    private List<OrgUser> getUserByOrgDepartmentId(String orgDepartmentId) {
        List<OrgUser> result = new ArrayList<>();
        String api = "/mozi/organization/pageOrganizationEmployeePositions";
        PostClient postClient = getExecutableClient().newPostClient(api);
        // 设置参数
        postClient.addParameter("returnTotalSize", "true");
        postClient.addParameter("pageSize", pageSize + "");
        postClient.addParameter("employeeStatus", "");
        postClient.addParameter("organizationCode", orgDepartmentId);
        postClient.addParameter("pageNo", "1");
        postClient.addParameter("tenantId", tenantId);
        // 调用API
        String apiResult = postClient.post();
        JSONObject jsonObject = JSONObject.parseObject(apiResult);
        boolean success = jsonObject.getBooleanValue("success");
        if (success) {
            JSONArray userArray = jsonObject.getJSONObject("content").getJSONArray("data");
            if (userArray != null) {
                for (Object obj : userArray) {
                    JSONObject user = (JSONObject)obj;
                    if (!"A".equals(user.getString("status"))) {
                        continue;
                    }
                    OrgUser orgUser = new OrgUser();
                    orgUser.setUserId(user.getString("employeeCode"));
                    orgUser.setName(user.getString("employeeName"));
                    orgUser.setModifiedTime(user.getDate("gmtCreate"));
                    orgUser.setGender(user.getString("empGender"));
                    orgUser.setExtend1(user.getString("empJobLevelCode"));
                    orgUser.setExtend2(user.getString("empBudgetedPostCode"));
                    orgUser.setExtend3(user.getString("gmtCreate"));
                    orgUser.setStatus("ENABLE");
                    JSONArray govEmployeePositions = user.getJSONArray("govEmployeePositions");
                    StringBuilder sbOrganizationCode = new StringBuilder();
                    StringBuilder sbEmpPosEmployeeRoleCode = new StringBuilder();
                    for (Object govEmployeePosition : govEmployeePositions) {
                        JSONObject govEp = (JSONObject)govEmployeePosition;
                        boolean mainJob = govEp.getBooleanValue("mainJob");
                        String organizationCode = govEp.getString("organizationCode");
                        String empPosEmployeeRoleCode = govEp.getString("empPosEmployeeRoleCode");
                        String status = govEp.getString("status");
                        if ("A".equals(status)) {
                            if (mainJob) {
                                sbOrganizationCode.insert(0, ",").insert(0, organizationCode);
                                sbEmpPosEmployeeRoleCode.insert(0, ",").insert(0, empPosEmployeeRoleCode);

                            } else {
                                sbOrganizationCode.append(organizationCode).append(",");
                                sbEmpPosEmployeeRoleCode.append(empPosEmployeeRoleCode).append(",");
                            }
                        }
                    }
                    if (sbOrganizationCode.indexOf(",") != -1) {
                        sbOrganizationCode.deleteCharAt(sbOrganizationCode.length() - 1);
                    }
                    if (sbEmpPosEmployeeRoleCode.indexOf(",") != -1) {
                        sbEmpPosEmployeeRoleCode.deleteCharAt(sbEmpPosEmployeeRoleCode.length() - 1);
                    }
                    orgUser.setDepartmentId(sbOrganizationCode.toString());
                    orgUser.setExtend1(sbEmpPosEmployeeRoleCode.toString());
                    updateUserId(orgUser);
                    result.add(orgUser);
                }
            }
            Integer totalSize = jsonObject.getJSONObject("content").getInteger("totalSize");
            int pageCount = totalSize % pageSize == 0 ? totalSize / pageSize : totalSize / pageSize + 1;
            if (pageCount == 1) {
                return result;
            } else {
                for (int i = 2; i <= pageCount; i++) {
                    postClient = getExecutableClient().newPostClient(api);
                    // 设置参数
                    postClient.addParameter("returnTotalSize", "true");
                    postClient.addParameter("pageSize", pageSize + "");
                    postClient.addParameter("employeeStatus", "");
                    postClient.addParameter("organizationCode", orgDepartmentId);
                    postClient.addParameter("pageNo", i + "");
                    postClient.addParameter("tenantId", tenantId);
                    // 调用API
                    apiResult = postClient.post();
                    jsonObject = JSONObject.parseObject(apiResult);
                    success = jsonObject.getBooleanValue("success");
                    if (success) {
                        userArray = jsonObject.getJSONObject("content").getJSONArray("data");
                        if (userArray != null) {
                            for (Object obj : userArray) {
                                JSONObject user = (JSONObject)obj;
                                OrgUser orgUser = new OrgUser();
                                orgUser.setUserId(user.getString("employeeCode"));
                                orgUser.setName(user.getString("employeeName"));
                                orgUser.setModifiedTime(user.getDate("gmtCreate"));
                                orgUser.setGender(user.getString("empGender"));
                                orgUser.setExtend1(user.getString("empJobLevelCode"));
                                orgUser.setExtend2(user.getString("empBudgetedPostCode"));
                                if ("A".equals(user.getString("status"))) {
                                    orgUser.setStatus("ENABLE");
                                } else {
                                    orgUser.setStatus("DISABLE");
                                }
                                orgUser.setDepartmentId(orgDepartmentId);
                                updateUserId(orgUser);
                                result.add(orgUser);
                            }
                        }
                    } else {
                        log.error("请求API异常,{}", jsonObject.getString("errorMsg"));
                    }
                }
            }
        } else {
            log.error("请求API异常,{}", jsonObject.getString("errorMsg"));
        }

        return result;
    }

    // 获取指定部门下（包括子部门）的所有用户，总数据要在10w以内，不然会丢失数据
    private void syncUserByOrgDepartmentId(String userId, String orgDepartmentId, Date date) {
        log.info("syncUserByOrgDepartmentId start >>>");

        String api = "/mozi/organization/pageOrganizationEmployeePositions";
        PostClient postClient;
        // 调用API
        String apiResult = "";
        long startTime = System.currentTimeMillis();
        boolean success = false;
        JSONObject jsonObject = null;
        while (!success) {
            try {
                postClient = getExecutableClient().newPostClient(api);
                // 设置参数
                postClient.addParameter("returnTotalSize", "true");
                postClient.addParameter("pageSize", pageSize + "");
                postClient.addParameter("employeeStatus", "");
                postClient.addParameter("organizationCode", orgDepartmentId);
                postClient.addParameter("pageNo", "1");
                postClient.addParameter("tenantId", tenantId);
                apiResult = postClient.post();
                jsonObject = JSONObject.parseObject(apiResult);
                success = jsonObject.getBooleanValue("success");
                if (!success) {
                    log.error(jsonObject.toJSONString());
                }
            } catch (Exception e) {
                log.debug(e.getMessage());
            }
            if ((System.currentTimeMillis() - startTime) / 1000 > retryLimitSeconds) {
                if (jsonObject != null) {
                    log.error(jsonObject.toJSONString());
                }
                log.error("调用api已超过{}秒，终止同步操作！", retryLimitSeconds);
                return;
            }
        }
        if (success) {
            Integer totalSize = jsonObject.getJSONObject("content").getInteger("totalSize");
            if (totalSize == null) {
                return;
            }
            log.debug("syncUserByOrgDepartmentId.totalSize={}", totalSize);
            int pageCount = totalSize % pageSize == 0 ? totalSize / pageSize : totalSize / pageSize + 1;
            log.debug("syncUserByOrgDepartmentId.pageCount={}", pageCount);
            for (int i = 1; i <= pageCount; i++) {
                List<OrgUser> result = new ArrayList<>();
                postClient = getExecutableClient().newPostClient(api);
                // 设置参数
                postClient.addParameter("returnTotalSize", "true");
                postClient.addParameter("pageSize", pageSize + "");
                postClient.addParameter("employeeStatus", "");
                postClient.addParameter("organizationCode", orgDepartmentId);
                postClient.addParameter("pageNo", i + "");
                postClient.addParameter("tenantId", tenantId);
                // 调用API
                apiResult = postClient.post();
                jsonObject = JSONObject.parseObject(apiResult);
                success = jsonObject.getBooleanValue("success");
                if (success) {
                    JSONArray userArray = jsonObject.getJSONObject("content").getJSONArray("data");
                    if (userArray != null) {
                        for (Object obj : userArray) {
                            JSONObject user = (JSONObject)obj;

                            OrgUser orgUser = new OrgUser();
                            orgUser.setUserId(user.getString("employeeCode"));
                            orgUser.setName(user.getString("employeeName"));
                            orgUser.setModifiedTime(user.getDate("gmtCreate"));
                            orgUser.setGender(user.getString("empGender"));
                            orgUser.setExtend1(user.getString("empJobLevelCode"));
                            orgUser.setExtend2(user.getString("empBudgetedPostCode"));
                            orgUser.setExtend3(user.getString("gmtCreate"));
                            if ("A".equals(user.getString("status"))) {
                                orgUser.setStatus("ENABLE");
                            } else {
                                orgUser.setStatus("DISABLE");
                            }
                            JSONArray govEmployeePositions = user.getJSONArray("govEmployeePositions");
                            StringBuilder sbOrganizationCode = new StringBuilder();
                            StringBuilder sbEmpPosEmployeeRoleCode = new StringBuilder();
                            for (Object govEmployeePosition : govEmployeePositions) {
                                JSONObject govEp = (JSONObject)govEmployeePosition;
                                boolean mainJob = govEp.getBooleanValue("mainJob");
                                String organizationCode = govEp.getString("organizationCode");
                                String empPosEmployeeRoleCode = govEp.getString("empPosEmployeeRoleCode");
                                String status = govEp.getString("status");
                                if ("A".equals(status)) {
                                    if (mainJob) {
                                        sbOrganizationCode.insert(0, ",").insert(0, organizationCode);
                                        sbEmpPosEmployeeRoleCode.insert(0, ",").insert(0, empPosEmployeeRoleCode);
                                    } else {
                                        sbOrganizationCode.append(organizationCode).append(",");
                                        sbEmpPosEmployeeRoleCode.append(empPosEmployeeRoleCode).append(",");
                                    }
                                }
                            }
                            if (sbOrganizationCode.indexOf(",") != -1) {
                                sbOrganizationCode.deleteCharAt(sbOrganizationCode.length() - 1);
                            }
                            if (sbEmpPosEmployeeRoleCode.indexOf(",") != -1) {
                                sbEmpPosEmployeeRoleCode.deleteCharAt(sbEmpPosEmployeeRoleCode.length() - 1);
                            }
                            orgUser.setDepartmentId(sbOrganizationCode.toString());
                            orgUser.setExtend1(sbEmpPosEmployeeRoleCode.toString());
                            updateUserId(orgUser);
                            result.add(orgUser);
                        }
                    }
                    if (result.size() > 0) {
                        syncUser(userId, date, result);
                    }
                } else {
                    log.error("请求API异常,{}", jsonObject.getString("errorMsg"));
                }
            }
        } else {
            log.error("请求API异常,{}", jsonObject.getString("errorMsg"));
        }
        log.info("<<<syncUserByOrgDepartmentId end");
    }

    // 根据用户code获取用户账户
    private void updateUserId(OrgUser orgUser) {
        String api = "/mozi/employee/listEmployeeAccountIds";
        PostClient postClient = getExecutableClient().newPostClient(api);
        // 设置参数
        postClient.addParameter("employeeCodes", orgUser.getUserId());
        postClient.addParameter("tenantId", tenantId);
        // 调用API
        String apiResult = postClient.post();
        JSONObject jsonObject = JSONObject.parseObject(apiResult);
        boolean success = jsonObject.getBooleanValue("success");
        if (success) {
            JSONArray userArray = jsonObject.getJSONObject("content").getJSONArray("data");
            if (userArray != null) {
                for (Object obj : userArray) {
                    JSONObject user = (JSONObject)obj;
                    orgUser.setUserId(user.getString("accountId"));
                    orgUser.setUsername(user.getString("accountId"));
                    orgUser.setSourceId(user.getString("accountId"));
                }
            }
        }
    }

    ///////////////////////////////////////////////////////////

    @Override
    public Map<String, Object> syncOrgAllV2(String userId) {
        Map<String, Object> result = new HashMap<>();
        String msg = "";

        try {
            Date date = new Date();
            if (StringUtils.isEmpty(topDepartmentId)) {
                msg = "同步组织架构V2失败，请确保application-syncorg.yml-topDepartmentId配置正确";
                result.put("status", false);
                result.put("msg", msg);
                log.error(msg);
                result.put("msg", msg);
                return result;
            } else {
                OrgDepartment orgDepartment = orgDepartmentMapper.selectOneByPrimaryKey(topDepartmentId);
                if (orgDepartment != null) {
                    corpId = orgDepartment.getCorpId();
                }
            }
            List<OrgDepartment> orgDepartmentList = getTopOrgDepartmentList();
            syncDepartmentListV2(userId, date, orgDepartmentList);

            // 绑定admin的corpId
            updateAdminCorpId();
            // 清空引擎缓存
            cleanCache();

            msg = "组织机构全量同步V2成功！";
            result.put("status", true);
            result.put("msg", msg);
        } catch (Exception e) {
            msg = "组织机构全量同步V2失败！";
            result.put("status", false);
            result.put("msg", msg);
        } finally {
            if (executableClient != null) {
                executableClient.destroy();
            }
        }
        return result;
    }

    @Override
    public Map<String, Object> syncOrgIncrementV2(String userId, String deptartmentId) {
        Map<String, Object> result = new HashMap<>();
        String msg = "";

        try {
            Date date = new Date();
            OrgDepartment orgDepartment = orgDepartmentMapper.selectOneByPrimaryKey(deptartmentId);
            updateOrgDepartmentDetails(orgDepartment);
            orgDepartmentMapper.delteLogicLikeQueryCode(deptartmentId);
            List<OrgDepartment> orgDepartmentList = new ArrayList<>();
            orgDepartmentList.add(orgDepartment);
            syncDepartmentListV2(userId, date, orgDepartmentList);

            // 绑定admin的corpId
            updateAdminCorpId();
            // 更新部门的叶子节点
            updateDepartmentLeaf();
            // 清空引擎缓存
            cleanCache();

            msg = "组织机构增量同步V2成功！";
            result.put("status", true);
            result.put("msg", msg);
        } catch (Exception e) {
            msg = "组织机构增量同步V2失败！";
            result.put("status", false);
            result.put("msg", msg);
        } finally {
            if (executableClient != null) {
                executableClient.destroy();
            }
        }
        return result;
    }

    private void syncDepartmentListV2(String userId, Date date, List<OrgDepartment> orgDepartmentList) {
        if (orgDepartmentList == null || orgDepartmentList.size() == 0) {
            return;
        }
        syncDepartmentList(userId, date, orgDepartmentList);
        for (OrgDepartment orgDepartment : orgDepartmentList) {
            orgDepartmentList = orgDepartmentMapper.selectByQueryCode(orgDepartment.getQueryCode());
            for (OrgDepartment orgDepartment1 : orgDepartmentList) {
                orgDepartmentList = getOrgDepartmentByParent(orgDepartment1.getId());
                syncDepartmentListV2(userId, date, orgDepartmentList);
            }
        }
    }

    private void syncDepartmentList(String userId, Date date, List<OrgDepartment> orgDepartmentList) {
        log.info("syncDept start>>>");

        // 部门的唯一标识号最为id
        List<OrgDepartment> tOrgDepartmentList = orgDepartmentMapper.selectByPrimaryKeyList(orgDepartmentList);
        List<String> idList = new ArrayList<>();
        for (OrgDepartment orgDepartment : tOrgDepartmentList) {
            idList.add(orgDepartment.getId());
        }
        // List<OrgDepartment> updateList = new ArrayList<>();
        // List<OrgDepartment> insertList = new ArrayList<>();
        for (OrgDepartment orgDepartment : orgDepartmentList) {
            orgDepartment.setSourceId(orgDepartment.getId());
            orgDepartment.setCreater(userId);
            orgDepartment.setModifier(userId);
            // orgDepartment.setExtend1("AutoAddUser:true");
            // orgDepartment.setExtend2("CreateDeptGroup:true");
            // orgDepartment.setExtend3(date.toString());
            orgDepartment.setCreatedTime(date);
            orgDepartment.setModifiedTime(date);
            orgDepartment.setIsShow(true);
            orgDepartment.setDeptType("YUNS_DEPT");
            orgDepartment.setCorpId(corpId);
            // 如果数据库存在，则更新，不存在则新增
            OrgDepartment tOrgDept = orgDepartmentMapper.selectOneByPrimaryKey(orgDepartment.getId());
            if (tOrgDept == null) {
                orgDepartmentMapper.insertByDepartment(orgDepartment);
            } else {
                orgDepartmentMapper.updateByDepartment(orgDepartment);
            }
            /* if (idList.contains(orgDepartment.getId())) {
                updateList.add(orgDepartment);
            } else {
                insertList.add(orgDepartment);
            }*/
        }

        // transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        /*      if (updateList.size() > 0) {
            int size = 1000;
            int loop = updateList.size() % size == 0 ? updateList.size() / size : updateList.size() / size + 1;
            for (int i = 0; i < loop; i++) {
                if (i == loop - 1) {
                    orgDepartmentMapper.updateByDepartmentList(updateList.subList(i * size, updateList.size()));
                } else {
                    orgDepartmentMapper.updateByDepartmentList(updateList.subList(i * size, i * size + size));
                }
            }
        }
        if (insertList.size() > 0) {
            int size = 1000;
            int loop = insertList.size() % size == 0 ? insertList.size() / size : insertList.size() / size + 1;
            for (int i = 0; i < loop; i++) {
                if (i == loop - 1) {
                    orgDepartmentMapper.insertByDepartmentList(insertList.subList(i * size, insertList.size()));
                } else {
                    orgDepartmentMapper.insertByDepartmentList(insertList.subList(i * size, i * size + size));
                }
            }
        }*/
        // dataSourceTransactionManager.commit(transactionStatus);

        log.info("<<<syncDept end");
    }

    @Override
    public Map<String, Object> syncUsersV2(String userId, String deptartmentId) {
        Map<String, Object> result = new HashMap<>();
        String msg;
        try {
            if (StringUtils.isEmpty(deptartmentId)) {
                OrgDepartment orgDepartment = orgDepartmentMapper.selectOneByPrimaryKey(topDepartmentId);
                if (orgDepartment == null) {
                    msg = "同步用户V2失败，请确保application-syncorg.yml-topDepartmentId配置正确";
                    result.put("status", false);
                    result.put("msg", msg);
                    log.error(msg);
                    result.put("msg", msg);
                    return result;
                }
                String queryCode = orgDepartment.getQueryCode().replaceAll("_", "\\\\_");
                List<OrgDepartment> orgDepartments = orgDepartmentMapper.selectLikeQueryCode(queryCode);
                for (OrgDepartment depart : orgDepartments) {
                    syncUserByCurrentOrgDepartmentId(userId, depart.getId(), new Date());
                }
            } else {
                List<OrgDepartment> orgDepartmentList = orgDepartmentMapper.selectLikeQueryCode(deptartmentId);
                for (OrgDepartment orgDepartment : orgDepartmentList) {
                    syncUserByCurrentOrgDepartmentId(userId, orgDepartment.getId(), new Date());
                }
            }

            // transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
            orgDeptUserMapper.clean();
            // dataSourceTransactionManager.commit(transactionStatus);
            // 清空引擎缓存
            cleanCache();
            executableClient.destroy();
            msg = "同步用户V2成功！";
            result.put("status", true);
            result.put("msg", msg);
        } catch (Exception e) {
            e.printStackTrace();
            msg = "同步用户V2失败：" + e.getMessage();
            result.put("status", false);
            result.put("msg", msg);
            log.error(msg);
        }
        return result;
    }

    // 获取指定部门下（当前部门）的用户
    private void syncUserByCurrentOrgDepartmentId(String userId, String orgDepartmentId, Date date) {
        log.info("syncUserByCurrentOrgDepartmentId start >>>");
        // 获取用户总数
        IntelligentGetClient intelligentGetClient =
            getExecutableClient().newIntelligentGetClient("/mozi/organization/pageOrganizationEmployeeCodes");
        OapiMoziOrganizationPageOrganizationEmployeeCodesRequest oapiMoziOrganizationPageOrganizationEmployeeCodesRequest =
            new OapiMoziOrganizationPageOrganizationEmployeeCodesRequest();
        oapiMoziOrganizationPageOrganizationEmployeeCodesRequest.setReturnTotalSize(true);
        oapiMoziOrganizationPageOrganizationEmployeeCodesRequest.setPageSize(pageSize);
        oapiMoziOrganizationPageOrganizationEmployeeCodesRequest.setOrganizationCode(orgDepartmentId);
        oapiMoziOrganizationPageOrganizationEmployeeCodesRequest.setPageNo(1);
        oapiMoziOrganizationPageOrganizationEmployeeCodesRequest.setTenantId(Long.valueOf(tenantId));
        OapiMoziOrganizationPageOrganizationEmployeeCodesResponse apiResult =
            intelligentGetClient.get(oapiMoziOrganizationPageOrganizationEmployeeCodesRequest);
        log.debug("apiResult={},{}", apiResult.getSuccess(), apiResult.getMessage());
        if (apiResult.getSuccess()) {
            OapiSpResultContent content = apiResult.getContent();
            log.debug("content={}", content);
            if (content.getSuccess()) {
                int totalSize = content.getTotalSize().intValue();
                log.debug("totalSize={}", totalSize);
                if (totalSize == 0) {
                    // 如果没有人结束改部门的同步
                    return;
                }
                int pageCount = totalSize % pageSize == 0 ? totalSize / pageSize : totalSize / pageSize + 1;
                log.debug("pageCount={}", pageCount);
                orgDeptUserMapper.deleteByDeptId(orgDepartmentId);
                for (int i = 1; i <= pageCount; i++) {
                    List<String> userCodeList = getUserCodeListPageByDeptIdAndPageNo(orgDepartmentId, i);
                    // 批量根据员⼯Code查询详情
                    IntelligentGetClient intelligentGetClientDetail =
                        getExecutableClient().newIntelligentGetClient("/mozi/employee/listEmployeesByCodes");
                    OapiMoziEmployeeListEmployeesByCodesRequest oapiMoziEmployeeListEmployeesByCodesRequest =
                        new OapiMoziEmployeeListEmployeesByCodesRequest();
                    oapiMoziEmployeeListEmployeesByCodesRequest.setEmployeeCodes(userCodeList);
                    oapiMoziEmployeeListEmployeesByCodesRequest.setTenantId(Long.valueOf(tenantId));
                    OapiMoziEmployeeListEmployeesByCodesResponse apiResultUserDetail =
                        intelligentGetClientDetail.get(oapiMoziEmployeeListEmployeesByCodesRequest);
                    log.debug("apiResultUserDetail={},{}", apiResultUserDetail.getSuccess(),
                        apiResultUserDetail.getMessage());
                    if (apiResultUserDetail.getSuccess()) {
                        OapiSpResultContent detailContent = apiResultUserDetail.getContent();
                        if (detailContent.getSuccess()) {
                            String resultData = detailContent.getData();
                            JSONArray userArray = JSONArray.parseArray(resultData);
                            List<OrgUser> result = new ArrayList<>();
                            if (userArray != null && userArray.size() > 0) {
                                for (Object obj : userArray) {
                                    JSONObject user = (JSONObject)obj;
                                    OrgUser orgUser = new OrgUser();
                                    orgUser.setUserId(user.getString("employeeCode"));
                                    orgUser.setName(user.getString("employeeName"));
                                    orgUser.setModifiedTime(user.getDate("gmtCreate"));
                                    orgUser.setGender(user.getString("empGender"));
                                    orgUser.setExtend3(user.getString("gmtCreate"));
                                    if ("A".equals(user.getString("status"))) {
                                        orgUser.setStatus("ENABLE");
                                    } else {
                                        orgUser.setStatus("DISABLE");
                                    }
                                    // 根据员工Code获取员工的任职
                                    updateUserOrgAndRole(orgUser);
                                    // 根据用户code获取用户账户
                                    updateUserId(orgUser);
                                    result.add(orgUser);
                                }
                            }
                            if (result.size() > 0) {
                                syncUser(userId, date, result);
                            }
                        } else {
                            log.error(detailContent.getResponseMessage());
                        }
                    } else {
                        log.error(apiResultUserDetail.getMessage());
                    }
                }
            } else {
                log.error(content.getResponseMessage());
            }
        } else {
            log.error(apiResult.getMessage());
        }

        log.info("<<< syncUserByCurrentOrgDepartmentId end");
    }

    // 根据员工Code获取员工的任职
    private void updateUserOrgAndRole(OrgUser orgUser) {
        IntelligentGetClient intelligentGetClientOrgAndRole =
            getExecutableClient().newIntelligentGetClient("/mozi/employee/listEmployeePositionsByEmployeeCode");
        OapiMoziEmployeeListEmployeePositionsByEmployeeCodeRequest oapiMoziEmployeeListEmployeePositionsByEmployeeCodeRequest =
            new OapiMoziEmployeeListEmployeePositionsByEmployeeCodeRequest();
        oapiMoziEmployeeListEmployeePositionsByEmployeeCodeRequest.setEmployeePositionStatus("A");
        oapiMoziEmployeeListEmployeePositionsByEmployeeCodeRequest.setEmployeePositionType("EMPLOYEE_POSITION_ALL");
        oapiMoziEmployeeListEmployeePositionsByEmployeeCodeRequest.setEmployeeCode(orgUser.getUserId());
        oapiMoziEmployeeListEmployeePositionsByEmployeeCodeRequest.setTenantId(Long.valueOf(tenantId));
        OapiMoziEmployeeListEmployeePositionsByEmployeeCodeResponse apiResultRole =
            intelligentGetClientOrgAndRole.get(oapiMoziEmployeeListEmployeePositionsByEmployeeCodeRequest);
        if (apiResultRole.getSuccess()) {
            OapiSpResultContent content = apiResultRole.getContent();
            if (content.getSuccess()) {
                String data = content.getData();
                JSONArray orgAndRoleArray = JSONArray.parseArray(data);
                StringBuilder sbOrganizationCode = new StringBuilder();
                StringBuilder sbEmpPosEmployeeRoleCode = new StringBuilder();
                for (Object orgAndRoleObj : orgAndRoleArray) {
                    JSONObject orgAndRole = (JSONObject)orgAndRoleObj;
                    boolean mainJob = orgAndRole.getBooleanValue("mainJob");
                    String organizationCode = orgAndRole.getString("organizationCode");
                    String empPosEmployeeRoleCode = orgAndRole.getString("empPosEmployeeRoleCode");
                    String status = orgAndRole.getString("status");
                    if ("A".equals(status)) {
                        if (mainJob) {
                            sbOrganizationCode.insert(0, ",").insert(0, organizationCode);
                            sbEmpPosEmployeeRoleCode.insert(0, ",").insert(0, empPosEmployeeRoleCode);
                        } else {
                            sbOrganizationCode.append(organizationCode).append(",");
                            sbEmpPosEmployeeRoleCode.append(empPosEmployeeRoleCode).append(",");
                        }
                    }
                }
                if (sbOrganizationCode.indexOf(",") != -1) {
                    sbOrganizationCode.deleteCharAt(sbOrganizationCode.length() - 1);
                }
                if (sbEmpPosEmployeeRoleCode.indexOf(",") != -1) {
                    sbEmpPosEmployeeRoleCode.deleteCharAt(sbEmpPosEmployeeRoleCode.length() - 1);
                }
                orgUser.setDepartmentId(sbOrganizationCode.toString());
                orgUser.setExtend1(sbEmpPosEmployeeRoleCode.toString());
            } else {
                log.error(content.getResponseMessage());
            }
        } else {
            log.error(apiResultRole.getMessage());
        }

    }

    // 分页获取用户Code
    private List<String> getUserCodeListPageByDeptIdAndPageNo(String orgDepartmentId, Integer pageNo) {
        List<String> userCodeList = new ArrayList<>();
        IntelligentGetClient intelligentGetClient =
            getExecutableClient().newIntelligentGetClient("/mozi/organization/pageOrganizationEmployeeCodes");
        OapiMoziOrganizationPageOrganizationEmployeeCodesRequest oapiMoziOrganizationPageOrganizationEmployeeCodesRequest =
            new OapiMoziOrganizationPageOrganizationEmployeeCodesRequest();
        oapiMoziOrganizationPageOrganizationEmployeeCodesRequest.setReturnTotalSize(true);
        oapiMoziOrganizationPageOrganizationEmployeeCodesRequest.setPageSize(pageSize);
        oapiMoziOrganizationPageOrganizationEmployeeCodesRequest.setOrganizationCode(orgDepartmentId);
        oapiMoziOrganizationPageOrganizationEmployeeCodesRequest.setPageNo(pageNo);
        oapiMoziOrganizationPageOrganizationEmployeeCodesRequest.setTenantId(Long.valueOf(tenantId));
        OapiMoziOrganizationPageOrganizationEmployeeCodesResponse apiResult =
            intelligentGetClient.get(oapiMoziOrganizationPageOrganizationEmployeeCodesRequest);

        if (apiResult.getSuccess()) {
            OapiSpResultContent content = apiResult.getContent();
            if (content.getSuccess()) {
                String data = content.getData();
                JSONArray userCodeArray = JSONArray.parseArray(data);
                for (Object obj : userCodeArray) {
                    userCodeList.add(obj.toString());
                }
            } else {
                log.error(content.getResponseMessage());
            }
        } else {
            log.error(apiResult.getMessage());
        }

        return userCodeList;
    }

    @Override
    public Map<String, Object> registerEventCallback(String eventTag, String callbackUrl) {
        boolean flag = true;
        StringBuilder msg = new StringBuilder();
        // executableClient保证单例
        IntelligentGetClient intelligentGetClient =
            getExecutableClient().newIntelligentGetClient("/openplatform/message/register_event_callback");
        OapiOpenplatformMessageRegisterEventCallbackRequest oapiOpenplatformMessageRegisterEventCallbackRequest =
            new OapiOpenplatformMessageRegisterEventCallbackRequest();
        // 消息事件标识
        oapiOpenplatformMessageRegisterEventCallbackRequest.setEventTag(eventTag);
        // 消息回调http地址
        oapiOpenplatformMessageRegisterEventCallbackRequest.setCallbackUrl(callbackUrl);
        // 获取结果
        OapiOpenplatformMessageRegisterEventCallbackResponse apiResult =
            intelligentGetClient.get(oapiOpenplatformMessageRegisterEventCallbackRequest);
        log.debug("registerEventCallback api result={}", apiResult.toString());
        if (!apiResult.getSuccess()) {
            if ("eventRegisterDao insert error".equals(apiResult.getErrorMsg())) {
                log.error("eventTag已注册，eventTag={}", eventTag);
                flag = false;
                msg.append("事件已注册");
            } else {
                log.error("eventTag注册失败，eventTag={}，result={}", apiResult.getErrorMsg());
                flag = false;
                msg.append(apiResult.getErrorMsg());
            }
        } else {
            log.error("eventTag注册成功，eventTag={}，result={}", eventTag, apiResult.getErrorMsg());
            msg.append(apiResult.getErrorMsg());
        }
        Map<String, Object> result = new HashMap<>();
        result.put("flag", flag);
        result.put("msg", msg);
        return result;
    }

    @Override
    public Map<String, Object> queryCallbackDefine() {
        Map<String, Object> result = new HashMap<>();
        boolean flag = true;
        StringBuilder msg = new StringBuilder();
        // 查询注册列表
        IntelligentGetClient intelligentGetClient =
            getExecutableClient().newIntelligentGetClient("/openplatform/message/query_callback_define");
        OapiOpenplatformMessageQueryCallbackDefineRequest oapiOpenplatformMessageQueryCallbackDefineRequest =
            new OapiOpenplatformMessageQueryCallbackDefineRequest();
        // 获取结果
        OapiOpenplatformMessageQueryCallbackDefineResponse apiResult =
            intelligentGetClient.get(oapiOpenplatformMessageQueryCallbackDefineRequest);
        if (apiResult.getSuccess()) {
            log.info("已注册回调={}", apiResult.getContent());
            msg.append("已注册回调=").append(apiResult.getContent());
        } else {
            log.error(apiResult.getErrorMsg());
            msg.append(apiResult.getErrorMsg());
            flag = false;
        }
        result.put("flag", flag);
        result.put("msg", msg);
        return result;
    }

    @Override
    public Map<String, Object> updateEventCallbackDefine(Long eventCallbackId, String callbackUrl) {
        Map<String, Object> result = new HashMap<>();
        boolean flag = true;
        StringBuilder msg = new StringBuilder();
        // executableClient保证单例
        IntelligentGetClient intelligentGetClient =
            getExecutableClient().newIntelligentGetClient("/openplatform/message/update_event_callback_define");
        OapiOpenplatformMessageUpdateEventCallbackDefineRequest oapiOpenplatformMessageUpdateEventCallbackDefineRequest =
            new OapiOpenplatformMessageUpdateEventCallbackDefineRequest();
        // 注册的回调id
        oapiOpenplatformMessageUpdateEventCallbackDefineRequest.setEventCallbackId(eventCallbackId);
        // 注册的http地址
        oapiOpenplatformMessageUpdateEventCallbackDefineRequest.setCallbackUrl(callbackUrl);
        // 获取结果
        OapiOpenplatformMessageUpdateEventCallbackDefineResponse apiResult =
            intelligentGetClient.get(oapiOpenplatformMessageUpdateEventCallbackDefineRequest);
        if (apiResult.getSuccess()) {
            log.info("{}更新成功{}", eventCallbackId, apiResult.getContent());
            msg.append(eventCallbackId).append("更新成功").append(apiResult.getContent());
        } else {
            log.error("{}更新失败{}", eventCallbackId, apiResult.getErrorMsg());
            flag = false;
        }
        result.put("flag", flag);
        result.put("msg", msg);
        return result;
    }

    @Override
    public Map<String, Object> deleteEventCallbackDefine(Long eventCallbackId) {
        Map<String, Object> result = new HashMap<>();
        boolean flag = true;
        StringBuilder msg = new StringBuilder();
        // executableClient保证单例
        IntelligentGetClient intelligentGetClient =
            executableClient.newIntelligentGetClient("/openplatform/message/delete_event_callback_define");
        OapiOpenplatformMessageDeleteEventCallbackDefineRequest oapiOpenplatformMessageDeleteEventCallbackDefineRequest =
            new OapiOpenplatformMessageDeleteEventCallbackDefineRequest();
        // 订阅回调的id
        oapiOpenplatformMessageDeleteEventCallbackDefineRequest.setEventCallbackId(eventCallbackId);
        // 获取结果
        OapiOpenplatformMessageDeleteEventCallbackDefineResponse apiResult =
            intelligentGetClient.get(oapiOpenplatformMessageDeleteEventCallbackDefineRequest);
        if (apiResult.getSuccess()) {
            log.info("{}删除成功", eventCallbackId);
            msg.append(eventCallbackId).append("删除成功");
        } else {
            log.error("{}删除失败{}", eventCallbackId, apiResult.getErrorMsg());
            flag = false;
        }
        result.put("flag", flag);
        result.put("msg", msg);
        return result;
    }

    @Override
    public Map<String, Object> queryCallbackFailed() {
        Map<String, Object> result = new HashMap<>();
        boolean flag = true;
        StringBuilder msg = new StringBuilder();
        // executableClient保证单例
        IntelligentGetClient intelligentGetClient =
            getExecutableClient().newIntelligentGetClient("/openplatform/message/query_callback_failed");
        OapiOpenplatformMessageQueryCallbackFailedRequest oapiOpenplatformMessageQueryCallbackFailedRequest =
            new OapiOpenplatformMessageQueryCallbackFailedRequest();
        // 获取结果
        OapiOpenplatformMessageQueryCallbackFailedResponse apiResult =
            intelligentGetClient.get(oapiOpenplatformMessageQueryCallbackFailedRequest);
        if (apiResult.getSuccess()) {
            log.info("查询回调失败信息成功{}", apiResult.getContent());
            msg.append("查询回调失败信息成功").append(apiResult.getContent());
        } else {
            log.error("查询回调失败信息失败{}", apiResult.getErrorMsg());
            flag = false;
        }
        result.put("flag", flag);
        result.put("msg", msg);
        return result;
    }

    @Override
    public Map<String, Object> retryCallbackFailed(Long eventCallbackFailedId) {
        Map<String, Object> result = new HashMap<>();
        boolean flag = true;
        StringBuilder msg = new StringBuilder();
        // executableClient保证单例
        IntelligentGetClient intelligentGetClient =
            executableClient.newIntelligentGetClient("/openplatform/message/retry_callback_failed");
        OapiOpenplatformMessageRetryCallbackFailedRequest oapiOpenplatformMessageRetryCallbackFailedRequest =
            new OapiOpenplatformMessageRetryCallbackFailedRequest();
        // 回调失败的id
        oapiOpenplatformMessageRetryCallbackFailedRequest.setEventCallbackFailedId(eventCallbackFailedId);
        // 获取结果
        OapiOpenplatformMessageRetryCallbackFailedResponse apiResult =
            intelligentGetClient.get(oapiOpenplatformMessageRetryCallbackFailedRequest);
        if (apiResult.getSuccess()) {
            log.info("{}重试失败回调成功{}", eventCallbackFailedId, apiResult.getContent());
            msg.append(eventCallbackFailedId).append("重试失败回调成功").append(apiResult.getContent());
        } else {
            log.error("{}重试失败回调失败{}", eventCallbackFailedId, apiResult.getErrorMsg());
            flag = false;
        }
        result.put("flag", flag);
        result.put("msg", msg);
        return result;
    }

    @Override
    public Map<String, Object> removeCallbackFailed(Long eventCallbackFailedId) {
        Map<String, Object> result = new HashMap<>();
        boolean flag = true;
        StringBuilder msg = new StringBuilder();
        // executableClient保证单例
        IntelligentGetClient intelligentGetClient =
            executableClient.newIntelligentGetClient("/openplatform/message/remove_callback_failed");
        OapiOpenplatformMessageRemoveCallbackFailedRequest oapiOpenplatformMessageRemoveCallbackFailedRequest =
            new OapiOpenplatformMessageRemoveCallbackFailedRequest();
        // 失败的id
        oapiOpenplatformMessageRemoveCallbackFailedRequest.setEventCallbackFailedId(1L);
        // 获取结果
        OapiOpenplatformMessageRemoveCallbackFailedResponse apiResult =
            intelligentGetClient.get(oapiOpenplatformMessageRemoveCallbackFailedRequest);
        if (apiResult.getSuccess()) {
            log.info("{}删除失败回调成功", eventCallbackFailedId);
            msg.append(eventCallbackFailedId).append("删除失败回调成功");
        } else {
            log.error("{}删除失败回调失败{}", eventCallbackFailedId, apiResult.getErrorMsg());
            flag = false;
        }
        result.put("flag", flag);
        result.put("msg", msg);
        return result;
    }
}
